/**
 * Created by gray on 2019/7/25.
 */
/**
 * amazonSOdetails.js
 *
 * @NAmdConfig ./configuration.json
 * @NApiVersion 2.x
 */
define(
    ['N/record', 'N/error', 'N/search','N/runtime'
        ,'../common/moment'
        ,'../common/utils'
        ,'./so.customer.builder'],
    function(record, error,search,runtime,moment,utils,customerBuilder) {
        var attribute = new Object();
        var method = new Object();

        method.createAndSaveOrder = function(builder,order) {
            var result = {};
            try{
                log.debug({
                    title:'the order context before init',
                    details:order
                });
                builder.method.init(order);

                result.storeId = order.storeId;

                log.debug({
                    title:'the order context after init',
                    details:order
                });

                if(method.orderExists(builder,order)){
                    throw 'order is exists';
                }

                var rec = record.create({
                    type: record.Type.SALES_ORDER,
                    isDynamic: true
                });
                //更换视图
                if(builder.attribute.formId){
                    rec.setValue('customform',builder.attribute.formId);
                }
                //更换视图结束
                //添加客户
                var customerId = customerBuilder.method.getCustomerId(builder,order);
                rec.setValue('entity',customerId);

                if(order.subsidiaryId){
                    rec.setValue('subsidiary',order.subsidiaryId);
                }

                var idMapValue = builder.attribute.orderIdMap_value;
                for(var key in idMapValue){
                    var id = idMapValue[key];
                    var value = utils.method.getJSONElementValue(order,key);
                    if(value&&value!=null&&value!==""){
                        try{rec.setValue(id,value);}catch(e){}
                    }
                }
                var idMapText = builder.attribute.orderIdMap_text;
                for(var key in idMapText){
                    var id = idMapText[key];
                    var text = utils.method.getJSONElementValue(order,key);
                    if(text&&text!=null&&text!==""){
                        try{rec.setText(id,text);}catch(e){}
                    }
                }
                order = builder.method.orderCustoming(rec,order);
                method.createItemLine(builder,rec,order);
                result.nsObjId = rec.save();
            }catch (e){
                log.debug({
                    title: 'e',
                    details: JSON.stringify(e)
                });
                var message = e.message;
                if(message&&message!=null&&message!=""){
                    e = e.message+','+e.stack;;
                }
                result.errorMsg = JSON.stringify(e);
            }
            return result;
        }

        method.orderExists = function(builder,order){
            var conditions = builder.attribute.orderExistsCondition;
            /*log.debug({
                title: 'order exists conditions',
                details: JSON.stringify(conditions)
            });*/
            var orderExistsFilter = [['mainline','is','T']];

            if(conditions.length&&conditions.length>0)
                for(var i=0;i<conditions.length;i++){
                    var condition = conditions[i];
                    var value ;
                    var recordId;
                    try{recordId = builder.attribute.orderIdMap_value[condition];}catch(e){};
                    if(!recordId){
                        try{recordId = builder.attribute.orderIdMap_text[condition];}catch(e){};
                    }
                    if(!recordId){
                        log.error({
                            title: 'config error',
                            details: "the custom order exists condistion ["+condition+"] not in order id map"
                        });
                        throw "config error : the custom order exists condistion ["+condition+"] not in order id map";
                    }
                    value = order[condition];
                    /*log.debug({
                        title: 'order exists condition nsid value',
                        details: condition+","+recordId+","+value
                    });*/
                    if(value){
                        orderExistsFilter[orderExistsFilter.length] = 'AND';
                        orderExistsFilter[orderExistsFilter.length] =
                            [recordId,'is',value];
                    }else{
                        throw " config error : cant find the order exists condition value [order."+condition+"] from order body";
                    }
                }

            log.debug({
                title: 'order exists filter',
                details: JSON.stringify(orderExistsFilter)
            });

            var orderExistsSearch = search.create({
                type:search.Type.SALES_ORDER,
                title: 'orderExistsSearch',
                columns: [],
                filters: orderExistsFilter
            })
            var results = orderExistsSearch.run().getRange({
                start: 0,
                end: 1
            });

            if (results && results.length && results.length > 0) {
                return true;
            } else {
                return false;
            }

        }

        method.createItemLine = function(builder,rec,order) {
            var items = order.items;
            log.debug({
                title: 'before items init',
                details:items
            });
            items = builder.method.itemLineCustoming(order);
            log.debug({
                title: 'after items init',
                details:items
            });
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                try{
                    //log.debug({title:'item details',details:JSON.stringify(item)});
                    rec.selectNewLine('item');
                    rec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        value:item.id
                    });
                    try{rec.setCurrentSublistValue('item','price',-1);}catch (e){
                        log.error({title:'set custom price level error',details:JSON.stringify(e)});
                    }

                    try{rec.setCurrentSublistValue('item','quantity',item.quantity);
                    }catch (e){
                        log.error({title:'set quantity error',details:JSON.stringify(e) +
                            ','+item.quantity
                        });
                    }
                    try{rec.setCurrentSublistValue('item', 'amount', item.amount);
                    }catch (e){
                        log.error({title:'set amount error',details:JSON.stringify(e)+
                        ','+item.amount});
                    }


                    var idMapValue = builder.attribute.itemIdMap_value;
                    //log.debug({title:'idMapValue',details:idMapValue});
                    for(var key in idMapValue){
                        var id = idMapValue[key];
                        var value = utils.method.getJSONElementValue(item,key);
                        //log.debug({title:'custom item',details:"id:"+id+",value+:"+value});
                        if(value&&value!=null&&value!==""){
                            try{rec.setCurrentSublistValue('item',id,value);}catch (e){}
                        }
                    }
                    var idMapText = builder.attribute.itemIdMap_text;
                    for(var key in idMapText){
                        var id = idMapText[key];
                        var Text = utils.method.getJSONElementValue(item,key);
                        if(Text&&Text!=null&&Text!==""){
                            try{rec.setCurrentSublistText('item',id,Text);}catch (e){}
                        }
                    }
                    rec.commitLine('item');
                }catch(e){
                    //log.debug({title:'create item line error',details:e.message+','+e.stack})
                    var message = e.message;
                    if(message&&message!=null&&message!=""){
                        e = e.message+','+e.stack;;
                    }
                    throw "accounting error : the item ["+item.sku+"] cant create line ."+e;
                }
            }
        }

        return {
            attribute: attribute,
            method:method
        };
    });